/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.wiki;

import com.google.inject.Inject;
import fitnesse.wikitext.WikiWidget;
import fitnesse.wikitext.widgets.ParentWidget;
import org.apache.commons.lang.StringUtils;
import org.xptracker.domain.Domain;
import org.xptracker.domain.NamedMap;
import org.xptracker.persistence.PersistenceManager;

import java.text.MessageFormat;

public class ExternalLinkWidget extends WikiWidget {
  @Inject
  private PersistenceManager mgr;

  @Inject
  private Domain domain;

  public static final String CUSTOM_LINKS = "custom-links";
  public static final String REGEXP = "\\w+:\\S+";
  private static final String ANCHOR_FMT = "<a class=\"ext-link\" href=\"{0}\">{1}: {2}</a>";
  private String content;

  public ExternalLinkWidget(ParentWidget parentWidget, String content) {
    super(parentWidget);
    this.content = content;
  }

  public String render() throws Exception {
    String[] chunks = content.split(":");
    if (chunks.length > 3) {
      return content;
    }

    int urlBase = (chunks.length == 3 ? 1 : 0);
    int idBase = (chunks.length == 3 ? 2 : 1);
    final String urlAlias = chunks[urlBase];
    final String id = chunks[idBase];

    return mgr.inTransaction(new PersistenceManager.UpdateHandler<String>() {
      public String doUpdate(PersistenceManager.UpdateReceiver receiver) {
        NamedMap namedMap = domain.getNamedMap(receiver, CUSTOM_LINKS);
        String hrefFormat = namedMap.map.get(urlAlias);
        if (StringUtils.isNotBlank(hrefFormat)) {
          String href = MessageFormat.format(hrefFormat, id);
          return MessageFormat.format(ANCHOR_FMT, href, urlAlias, id);
        } else {
          return content;
        }
      }
    });
  }
}
